<?php

/**
 * Subclass for representing a row from the 'challenge' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Challenge extends BaseChallenge
{
	private $p1 ;
	private $p2 ;

	public function setP1($p)	{
		$this->p1 = $p ;
	}

	public function setP2($p)	{
		$this->p2 = $p ;
	}
	
	public function getP1()	{
		return $this->p1 ;
	}

	public function getP2()	{
		return $this->p2 ;
	}

	public function setIsRefused($b)	{
		parent::setIsRefused($b) ;
		if ($b == 1)	{
			$this->setRefusedAt(date('Y-m-d H:i:s')) ;
		}
	}

	/* validation of a challenge with points calculation */
	public function setIsValid($b)	{
		parent::setIsValid($b) ;
		
		if ($b == 1)	{
			$this->setValidationDt(date('Y-m-d H:i:s')) ;
			
			$p1 = $this->getP1() ;
			$p2 = $this->getP2() ;
			
			$p1_points = $p1->getPoints() ;
			$p2_points = $p2->getPoints() ;
			
			$this->setP1Points($p1_points) ;
			$this->setP2Points($p2_points) ;
	 		$this->setP1Rank($p1->getRank()) ;
  		$this->setP2Rank($p2->getRank()) ;
			
			$p1_rating = 1 / (10^(-($p1_points - $p2_points)/400) + 1) ;
			$p2_rating = 1 / (10^(-($p2_points - $p1_points)/400) + 1) ;
			
			if ($this->getIsDraw() == 1)	{
				$p1_game_points = 0.5 ;
				$p2_game_points = 0.5 ;
			} else {
				$p1_game_points = 1 ;
				$p2_game_points = 0 ;
			}
			
			$k = 32 ;
			
			$p1_new_elo = $p1_points + $k * ($p1_game_points - $p1_rating) ;
			$p2_new_elo = $p2_points + $k * ($p2_game_points - $p2_rating) ; 
			
			if ($p1_game_points == 0 )	{
				$p1->addLoss() ;
				$p2->addWin() ;
			} else if ($p1_game_points == 1) {
				$p1->addWin() ;
				$p2->addLoss() ;
			} else if ($p1_game_points == 0.5)	{
				$p1->addDraw() ;
				$p2->addDraw() ;
			}
	
			$p1->setPoints($p1_new_elo) ;
			$p2->setPoints($p2_new_elo) ;
			
			$p1->save() ;
			$p2->save() ;
		}
	}
}
